package cn.zhiquxing.excel;

import cn.zhiquxing.vo.ImportData;
import com.alibaba.excel.context.AnalysisContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

@Component
public class ExcelDataListener extends AnalysisEventListener<ImportData> {
    private static final int BATCH_SIZE = 200;
    
    @Autowired
    private DataProcessService dataProcessService;
    
    private List<ImportData> cachedDataList = new ArrayList<>(BATCH_SIZE);
    
    @Override
    public void invoke(ImportData data, AnalysisContext context) {
        cachedDataList.add(data);
        if (cachedDataList.size() >= BATCH_SIZE) {
            processBatch();
            cachedDataList.clear();
        }
    }
    
    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {
        if (!cachedDataList.isEmpty()) {
            processBatch();
            cachedDataList.clear();
        }
    }
    
    private void processBatch() {
        dataProcessService.processBatchData(cachedDataList);
    }
}